<template>
  <div class="flex flex-col">
    <a-card class="rounded mb-[10px]" :body-style="{padding: '12px 16px', }" :bordered="false">
      <a-form layout="inline" v-model="searchForm" v-show="showSearch" class="mb20">
        <a-form-item label="姓名">
          <a-input
            v-model="searchForm.UserName"
            placeholder="请输入真实姓名"
            @keyup.enter.native="search"
          />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input
            v-model="searchForm.UserPhone"
            placeholder="请输入手机号"
            @keyup.enter.native="search"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click.native.prevent="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="() => searchForm = {}">重置</a-button>
        </a-form-item>
      </a-form>
      <div class="h-full flex justify-between items-center mt-[5px]">
        <div>
          <!-- <a-button type="primary" icon="plus" @click="create" ghost>创建</a-button> -->
        </div>
        <div>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>
      </div>
    </a-card>
    <a-card
      class="min-h-[400px] h-full rounded overflow-x-auto"
      :body-style="{padding: '12px 16px'}"
      :bordered="false"
    >
      <a-table
        ref="table"
        size="middle"
        class="h-full"
        :columns="columns"
        :dataSource="list"
        :pagination="pagination"
        @change="tableChange"
        :loading="listLoading"
        :rowKey="(record,index)=>{return index}"
      >
        <template v-for="(col, i) in editColumns" :slot="col" slot-scope="text, record">
          <a-input
            :key="col"
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            :placeholder="columns[i].title"
            @change="e => handleChange(e.target.value, record.key, col)"
          />
          <template v-else>{{ text }}</template>
        </template>
        <template slot="build" slot-scope="text, record">{{text==0?'未归属':text}}</template>
        <template slot="doctorStr" slot-scope="text, record">
          <span v-if="!text.split(',')[0]">未绑定</span>
          <span v-else-if="text.split(',').length<=3">{{text}}</span>
          <span v-else>{{text.split(',').slice(0,3).join(',')}} ...</span>
        </template>

        <template slot="UserStatus" slot-scope="text,record">
          <a-switch
            checked-children="启用"
            un-checked-children="禁用"
            default-checked
            :checked="text==1"
            @change="changeStatus(record.UserId)"
            :loading="record.UserId==userId"
          />
        </template>
        <template slot="action" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable" class="flex">
              <a-button type="link" block @click="() => save(record)">保存</a-button>
              <a-popconfirm title="确认取消修改?" @confirm="() => cancel(record.UserId)">
                <a-button type="link" block>返回</a-button>
              </a-popconfirm>
            </span>
            <span v-else class="flex">
              <a-button type="link" block @click="details(record.UserId)">查看</a-button>
              <a-button type="link" block @click="bind(record.UserId)">归属</a-button>
            </span>
          </div>
        </template>
      </a-table>
    </a-card>
    <bind-attribution ref="bindAttribution" @succeed="init" />
  </div>
</template>

<script>
import toolbar from '@/mixins/toolbar-mixin'
import { getAssistantList, changeAssistantStatus } from '@/api/index'
import BindAttribution from './components/bindAttribution.vue'
const columns = [
  {
    title: '助理ID',
    className: 'min-w-90p',
    dataIndex: 'UserId',
    align: 'center',
    scopedSlots: { customRender: 'UserId' },
  },
  {
    title: '姓名',
    className: 'min-w-120p',
    dataIndex: 'UserName',
    align: 'center',
    scopedSlots: { customRender: 'UserName' },
  },
  {
    title: '归属',
    className: 'min-w-120p',
    dataIndex: 'build',
    align: 'center',
    scopedSlots: { customRender: 'build' },
  },

  {
    title: '手机号',
    className: 'min-w-150p',
    dataIndex: 'UserPhone',
    align: 'center',
    scopedSlots: { customRender: 'UserPhone' },
  },
  {
    title: '绑定医生',
    className: 'min-w-90p',
    dataIndex: 'doctorStr',
    align: 'center',
    scopedSlots: { customRender: 'doctorStr' },
  },
  {
    title: '状态',
    className: 'min-w-90p',
    dataIndex: 'UserStatus',
    align: 'center',
    scopedSlots: { customRender: 'UserStatus' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width: '120px',
    scopedSlots: { customRender: 'action' },
  },
]
const editColumns = ['phone', 'idCard', 'openid']

export default {
  mixins: [toolbar],
  components: { BindAttribution },
  data() {
    return {
      columns,
      editColumns,
      /** 搜索查询参数 */
      searchForm: {
        UserName: undefined,
        UserPhone: undefined,
      },
      /**分页 */
      pagination: {
        current: 1, //当前页
        pageSize: 10, //每页条数
        total: 0, //总条数
        showQuickJumper: true,
        hideOnSinglePage: true,
        showTotal: (total) => `共 ${total} 条数据`,
      },
      /**table数据 */
      list: [],

      //表格Loading
      listLoading: false,
      //抽屉提交按钮loading
      loading: false,
      userId: 0,
    }
  },
  methods: {
    init() {
      this.pagination.current = 1
      this.getList()
    },
    /**
     * 搜索
     */
    search() {
      this.pagination.current = 1
      this.getList()
    },
    //分页
    tableChange(pagination) {
      this.pagination = pagination
      this.getList()
    },
    /**
     * 获取列表
     */
    async getList() {
      this.listLoading = true
      const { current, pageSize } = this.pagination
      try {
        const { data } = await getAssistantList({
          ...{ page: current, pageSize },
          ...this.searchForm,
        })
        const { Page, PageSize, Total, Lists } = data
        this.list = Lists || []
        this.pagination = {
          current: Page,
          pageSize: PageSize,
          total: Total,
        }
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.listLoading = false
      }
    },
    /**
     * 切换状态
     * @param {*} userId
     */
    async changeStatus(id) {
      try {
        this.userId = id
        await changeAssistantStatus({ id })
        this.$message.success('修改成功')
        this.init()
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.userId = 0
      }
    },
    handleChange(value, key, column) {
      const newData = [...this.list]
      const target = newData.find((item) => key === item.UserId)
      if (target) {
        target[column] = value
        this.list = newData
      }
    },
    create() {},
    bind(id) {
      console.log('id', id)
      this.$refs.bindAttribution.open(id)
    },
    /**
     * 查看资料
     * @param {*} id
     */
    details(id) {
      this.$router.push({ path: '/user/assistantDetail', query: { id } })
    },
    /**
     * 修改资料
     * @param {*} key
     */
    edit(key) {
      const newData = [...this.list]
      const target = newData.find((item) => key === item.UserId)
      target._originalData = { ...target }
      target.editable = true
      if (target) {
        this.list = newData
      }
      console.log('this.list', this.list)
    },
    /**
     * 保存
     * @param {*} key
     */
    async save(record) {
      this.listLoading = true
      const { DhlLevelName, UserId } = record
      if (!DhlLevelName) {
        this.listLoading = false
        this.$message.error('请填写完整成员信息。')
        return
      }
      try {
        await editHospitalLevel({ id: Id, name: DhlLevelName })
        const target = this.list.find((item) => UserId === item.UserId)
        target.editable = false
        this.$message.success('修改成功')
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.listLoading = false
      }
    },
    /**
     * 取消修改
     * @param {*} key
     */
    cancel(key) {
      const newData = [...this.list]
      const target = newData.find((item) => key === item.UserId)
      console.log('target', target)
      Object.keys(target).forEach((key) => {
        if (key != '_originalData') target[key] = target._originalData[key]
      })
      target.editable = false
      target._originalData = undefined
      if (target) {
        this.list = newData
      }
    },
  },
  created() {
    this.init()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
